/* 
 * (C) 2013 Daniel Garcia <contacto {at} danigarcia.org>
 * 
 * http://danigarcia.org
 * 
 * This file is part of BlackList.
 * 
 * BlackList is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * BlackList is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with BlackList.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.danigarcia.android.blacklist.service;

import org.danigarcia.android.blacklist.MainActivity;
import org.danigarcia.android.blacklist.R;
import org.danigarcia.android.blacklist.database.ConfigManager;
import org.danigarcia.android.blacklist.database.DataManager;
import org.danigarcia.android.blacklist.phone.IncomingCallListener;
import org.danigarcia.android.blacklist.phone.IncomingCallReceiver;
import org.danigarcia.android.blacklist.phone.SMSReceiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class BlockingService extends Service {

	private static final String TAG = BlockingService.class.getName();
	public static final String BLOCKING_SERVICE = "org.danigarcia.android.blacklist.service.BlockingService.BLOCKING_SERVICE";
	public static final int REQUEST_CODE = 230382;
	
	private TelephonyManager tm;
	private IncomingCallListener callListener;
	private IncomingCallReceiver callReceiver;
	private SMSReceiver smsReceiver;
	private DataManager dManager;
	private NotificationManager nManager;
	private int blockedCalls = 0;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

		initNotification();
        return START_STICKY;
    }
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.d(TAG, "onCreate()");
		
		tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		//tm = (TelephonyManager) getSystemService("phone");
		//tm = (TelephonyManager) getSystemService("phone_msim");
				
		dManager = new DataManager(getApplicationContext(), DataManager.DB_NAME, null, DataManager.DB_VERSION);
		ConfigManager.init(getApplicationContext());
		
		/*
		 * UPDATE 2013/10/26 : 
		 * Class not used anymore because Dual-SIM issues with secondary SIM (it's not 
		 * detecting secondary SIM events). Use IncomingCallReceiver instead. 
		 *	 
		 * //callListener = new IncomingCallListener(this, dManager, tm);
		 * //tm.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
		 */
		
		callReceiver = new IncomingCallReceiver(this, dManager, tm);
		
		IntentFilter stateFilter = new IntentFilter(IncomingCallReceiver.PHONE_STATE);
		stateFilter.setPriority(100);
		this.registerReceiver(callReceiver, stateFilter);
		
		if(ConfigManager.getBoolean(ConfigManager.KEY_FILTER_SMS))
		{
			Log.d(TAG, "onCreate(): Activating SMSReceiver");
			smsReceiver = new SMSReceiver(dManager);
			IntentFilter smsFilter = new IntentFilter(SMSReceiver.SMS_RECEIVED);
			smsFilter.setPriority(100);
			this.registerReceiver(smsReceiver, smsFilter);
		}
		else
			Log.d(TAG, "onCreate(): SMSReceiver is not active");
	}
	
	@Override
	public void onDestroy() {
		stopForeground(true);
		if(smsReceiver != null)
			this.unregisterReceiver(smsReceiver);
		if(callReceiver != null)
			this.unregisterReceiver(callReceiver);
		if(callListener != null)
			tm.listen(callListener, PhoneStateListener.LISTEN_NONE);
		
		tm = null;
		callListener = null;
		callReceiver = null;
		dManager = null;
		
		Log.d(TAG, "onDestroy()");
		
		super.onDestroy();
	}

	private Notification generateNotification(boolean blockedCall, boolean blockedSMS, String phoneNumber)
	{
		Notification notification = null;
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
		
		builder.setContentIntent(pendingIntent);
		builder.setSmallIcon(R.drawable.ic_stat_no_calls);
		builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_no_calls));
		if(blockedCall)
		{
			builder.setTicker(String.format(getString(R.string.msgBlockedCall), phoneNumber));
		}
		else if(blockedSMS)
		{
			builder.setTicker(String.format(getString(R.string.msgBlockedSms), phoneNumber));
		}
		else
		{
			builder.setTicker(getString(R.string.blockingCalls));
		}
		
		builder.setWhen(System.currentTimeMillis());
		builder.setAutoCancel(true);
		builder.setContentInfo(String.valueOf(blockedCalls++));
		builder.setContentTitle(getString(R.string.app_name));
		builder.setContentText(getString(R.string.blockingCalls));
		
		notification = builder.build();
		
		return notification;
	}

	private void initNotification()
	{
		Log.d(TAG, "initNotification()");
		nManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = generateNotification(false, false, "");
		startForeground(REQUEST_CODE, notification);
	}
	
	public void updateNotification(String phoneNumber, boolean isCall, boolean isSms)
	{
		Log.d(TAG, String.format("updateNotification(): Requesting update: %s", phoneNumber));
		Notification notification = generateNotification(isCall, isSms, phoneNumber);
		nManager.notify(REQUEST_CODE, notification);
	}
	
}
